package org.ccay.core.exception.impl;

import javax.inject.Named;

import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;

/**
 * 异常配置收集器
 * 	
 * 
 * @since 2013-4-22
 */
@Named
public class ExceptionConfigCollector implements BeanDefinitionRegistryPostProcessor  {
	
	private static final ILogger logger = CcayLoggerFactory.getLogger(ExceptionConfigCollector.class);
	 

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)
	 */
	public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
		
	}

	private static final String className = ExceptionConfigBean.class.getName();
	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry)
	 */
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry bdr) throws BeansException {
		String[] beans = bdr.getBeanDefinitionNames();
		logger.debug("Beans Count:" + bdr.getBeanDefinitionCount());
		for(String bean : beans){
			BeanDefinition beanDefinition = bdr.getBeanDefinition(bean);
			if(beanDefinition != null &&  className.equals(beanDefinition.getBeanClassName())){
				//logger.debug("Before parse exception bean:" + bean);
				MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
				ExceptionConfigBean ecb = new ExceptionConfigBean();
				ecb.setZhCN(((TypedStringValue) propertyValues.getPropertyValue("zhCN").getValue()).getValue());
				ecb.setEnUS(((TypedStringValue) propertyValues.getPropertyValue("enUS").getValue()).getValue());
				ecb.setErrorCode(bean);				
				
				ExceptionMessageManager.buildConfig(ecb);
				
				bdr.removeBeanDefinition(bean);
			}
		}
		
		logger.debug("Beans Count after clean:" + bdr.getBeanDefinitionCount());		 
	}
}
